﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsPageContentTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    ///<summary>
    ///Page Content Business Object
    ///</summary>

    public class PageContents : BOBase
    {
        #region Types


        #endregion

        #region Constants


        #endregion

        #region Contructor / Disposal

        ///<summary>
        /// Default Constructor.
        ///</summary>
        protected PageContents()
        { 
        }

        #endregion 

        #region Public Properties

        /// <summary>
        /// PKID of the Page.
        /// </summary>
        public int PageID
        {
            get { return (_pageID); }
            set
            {
                if (OnPropertyChanging("PageID", _pageID, value))
                {
                    int oldValue = _pageID;
                    _pageID = value;
                    OnPropertyChanged("PageID", oldValue, value);
                }
            }
        } private int _pageID = 0;

        /// <summary>
        /// Page Name.
        /// </summary>
        public string PageName
        {
            get { return _pageName; }
            set
            {
                if (_pageName != value)
                {
                    if (OnPropertyChanging("PageName", _pageName, value))
                    {
                        string oldValue = _pageName;
                        _pageName = value;
                        OnPropertyChanged("PageName", oldValue, value);
                    }
                }
            }
        }  private string _pageName = null;

        /// <summary>
        /// Date/time at which the Page Content was Added.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the Page Content was Updated.
        /// </summary>
        public DateTime? UpdatedDate
        {
            get { return _updatedDate; }
            set
            {
                if (_updatedDate != value)
                {
                    if (OnPropertyChanging("UpdatedDate", _updatedDate, value))
                    {
                        DateTime? oldValue = _updatedDate;
                        _updatedDate = value;
                        OnPropertyChanged("UpdatedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updatedDate = null;

        /// <summary>
        /// Page Title.
        /// </summary>
        public string PageTitle
        {
            get { return _pageTitle; }
            set
            {
                if (_pageTitle != value)
                {
                    if (OnPropertyChanging("PageTitle", _pageTitle, value))
                    {
                        string oldValue = _pageTitle;
                        _pageTitle = value;
                        OnPropertyChanged("PageTitle", oldValue, value);
                    }
                }
            }
        }  private string _pageTitle = null;


        /// <summary>
        /// Meta Title.
        /// </summary>
        public string MetaTitle
        {
            get { return _metaTitle; }
            set
            {
                if (_metaTitle != value)
                {
                    if (OnPropertyChanging("MetaTitle", _metaTitle, value))
                    {
                        string oldValue = _metaTitle;
                        _metaTitle = value;
                        OnPropertyChanged("MetaTitle", oldValue, value);
                    }
                }
            }
        }  private string _metaTitle = null;


        /// <summary>
        /// Meta Keywords.
        /// </summary>
        public string MetaKeywords
        {
            get { return _metaKeywords; }
            set
            {
                if (_metaKeywords != value)
                {
                    if (OnPropertyChanging("MetaKeywords", _metaKeywords, value))
                    {
                        string oldValue = _metaKeywords;
                        _metaKeywords = value;
                        OnPropertyChanged("MetaKeywords", oldValue, value);
                    }
                }
            }
        }  private string _metaKeywords = null;


        /// <summary>
        /// Meta Description.
        /// </summary>
        public string MetaDescription
        {
            get { return _metaDescription; }
            set
            {
                if (_metaDescription != value)
                {
                    if (OnPropertyChanging("MetaDescription", _metaDescription, value))
                    {
                        string oldValue = _metaDescription;
                        _metaDescription = value;
                        OnPropertyChanged("MetaDescription", oldValue, value);
                    }
                }
            }
        }  private string _metaDescription = null;


        /// <summary>
        /// Meta Description.
        /// </summary>
        public string PageContent
        {
            get { return _pageContent; }
            set
            {
                if (_pageContent != value)
                {
                    if (OnPropertyChanging("PageContent", _pageContent, value))
                    {
                        string oldValue = _pageContent;
                        _pageContent = value;
                        OnPropertyChanged("PageContent", oldValue, value);
                    }
                }
            }
        }  private string _pageContent = null;


        #endregion

        #region Public Methods

        #region GetAllPageContents

        ///<summary>
        ///Returns a collection of All Pages
        ///</summary>

        public static PageContentsCollection GetAllPageContents()
        {
            PageContentTableAdapter adapter = new PageContentTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsPageContent.PageContentDataTable tbl = adapter.GetData(null);

            PageContentsCollection list = new PageContentsCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsPageContent.PageContentRow row in tbl.Rows)
                {
                    PageContents pgc = new PageContents();
                    RelationalToObject(pgc, row);
                    list.Add(pgc);
                }
            }

            return (list);
        }

        #endregion

        #region GetPageContentByID

        /// <summary>
        /// Returns an PageContent object for the specified 'PageID' or null if no PageID with the specified parameter(s) exists.
        /// </summary>
        public static PageContents GetPageContentByID(int pageid)
        {
            PageContentTableAdapter adapter = new PageContentTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsPageContent.PageContentDataTable tbl = adapter.GetData(pageid);

            if (tbl.Rows.Count == 1)
            {
                PageContents pgc = new PageContents();
                RelationalToObject(pgc, tbl.Rows[0]);
                return (pgc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'PageID' returned more than one Page record.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified SubAdmin.
        /// </summary>
        public static void Update(PageContents obj)
        {
            bool updatepagecontent = true;

            //do not validate invalid objects
            //if (!obj.Validate())
            //{
            //    StringBuilder sb = new StringBuilder(2048);
            //    sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
            //    foreach (ValidationError err in obj.Errors)
            //        sb.Append("\n* " + err.Element + ": " + err.Message);

            //    throw new InvalidObjectException(sb.ToString());
            //}
            //else
            //{
            //    updatepagecontent = (obj.ObjState != ObjectState.Unchanged);

            //    if (!updatepagecontent)
            //        return;
            //}

            //ObjectState originalObjectState = obj.ObjState;

            dsPageContent.PageContentDataTable tbl = null;
            if (updatepagecontent)
            {
                PageContentTableAdapter adapter = new PageContentTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsPageContent.PageContentDataTable();
                dsPageContent.PageContentRow row = tbl.NewPageContentRow();
                ObjectToRelational(obj, tbl, row);

               adapter.Update(tbl);
            }

        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (PageID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("PageID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                //if ((UserLogin == null) || (UserLogin.Trim().Length == 0))
                //{
                //    Errors.Add(new ValidationError("UserLogin", "UserLogin is required.", ValidationError.Severity.Error));
                //}
                //else if (ObjState == ObjectState.Added)
                //{
                //    // Ensure that the UserName is unique within the associated Retailer.
                //    //if (AppUser.GetUserByUsernameRetailerID(UserLoginID, RetailerID) != null)
                //    //{
                //    //    string retailerName = Retailer.DisplayName;
                //    //    Errors.Add(new ValidationError("UserName", "Username must be unique; \"" + UserLoginID + "\" is already present in Retailer \"" + custName + "\".", ValidationError.Severity.Error));
                //    //}
                //}

                // TODO: Check the Company's AuthMethod: If it's PKID_LocalDB, then Password is required.

                // FirstName is required.
                //if ((FirstName == null) || (FirstName.Length == 0))
                //    Errors.Add(new ValidationError("FirstName", "FirstName is required.", ValidationError.Severity.Error));

                //// LastName is required.
                //if ((LastName == null) || (LastName.Length == 0))
                //    Errors.Add(new ValidationError("LastName", "LastName is required.", ValidationError.Severity.Error));

                //// TODO: Regex validate the email address format.

                //// CreatedByID is required.
                //if (CreatedByID <= 0)
                //    CreatedByID = SubAdmin.Current.UserID;

                //// Ensure LastModifiedBy is current.
                //if (ObjState == ObjectState.Modified)
                //    LastModifiedByID = SubAdmin.Current.UserID;
            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("PageContents: PKID={0}, Page={1}", PageID, PageName));
        }

        #endregion

        #endregion

        #region Privates

        #region UpdatePageContent

        ///// <summary>
        ///// Method increments the LoginCount property of the specified 'user' and invokes a
        ///// stored-procedure to store the new count without changing the LastModifiedByID and
        ///// LastModifiedDate fields of the corresponding User row in the database.
        ///// </summary>
        //private static void IncrementLoginCount(SubAdmin user)
        //{
        //    user.LoginCount++;

        //    SubAdminsTableAdapter adapter = new SubAdminsTableAdapter();
        //    adapter.Connection = AppSettings.GetDbConn();
        //    dsSubAdmin.SubAdminsDataTable tbl = new dsSubAdmin.SubAdminsDataTable();

        //    dsSubAdmin.SubAdminsRow row = tbl.NewSubAdminsRow();
        //    ObjectToRelational(user, tbl, row);

        //    adapter.UpdateLoginCount(tbl, user.UserID, user.LoginCount);

        //    RelationalToObject(user, tbl.Rows[0]);
        //}

        #endregion


        #endregion

    }

    ///<summary>
    ///Collection of 0 or more PageContents Objects
    ///</summary>

    public class PageContentsCollection : List<PageContents>
    {
        #region Types

        #endregion 

        #region Public Methods

        #region FindByPageID

        public PageContents FindByPageID(int pageID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].PageID == pageID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion 

    }
}
